//
//  LYSideslipCell.m
//  LYSideslipCellDemo
//
//  Created by Louis on 16/7/5.
//  Copyright © 2016年 Louis. All rights reserved.
//

#import "LYSideslipCell.h"

#import "SideslipBtn.h"

@interface LYSideslipCellAction ()
@property (nonatomic, copy) void (^handler)(LYSideslipCellAction *action, NSIndexPath *indexPath);
@end
@implementation LYSideslipCellAction
+ (instancetype)rowActionWithBackgroundColor:(UIColor *)backgroundColor title:(nullable NSString *)title titleColor:(nullable UIColor *)titleColor titleFontSize:(CGFloat)fontSize image:(nullable UIImage *)image speed:(CGFloat)speed handler:(void (^)(LYSideslipCellAction *action, NSIndexPath *indexPath))handler {
    LYSideslipCellAction *action = [LYSideslipCellAction new];
    action.title = title;
    action.handler = handler;
    action.backgroundColor = backgroundColor;
    action.titleColor = titleColor;
    action.fontSize = fontSize;
    action.image = image;
    action.speed = speed;
    return action;
}

- (CGFloat)margin {
    return _margin == 0 ? 15 : _margin;
}
@end

@interface LYSideslipCell () <UIGestureRecognizerDelegate>
@property (nonatomic, assign) float btnTotalFloat;//全部按钮显示临界值（宽度）
@end

@implementation LYSideslipCell {
    UITableView *_tableView;
    UIPanGestureRecognizer *_panGesture;
}

#pragma mark - Life Cycle
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self setupSideslipCell];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self setupSideslipCell];
    }
    return self;
}

- (void)setupSideslipCell {
    _panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(contentViewPan:)];
    _panGesture.delegate = self;
    [self.contentView addGestureRecognizer:_panGesture];
    self.contentView.backgroundColor = [UIColor whiteColor];
    [self.contentView addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"frame"]) {
        for (SideslipBtn *btn in [_btnContainView subviews]) {
            CGRect frame = btn.frame;
            if (self.contentView.frame.origin.x < 0) {
                if (self.contentView.frame.origin.x > -_btnTotalFloat) {
                    frame.origin.x = self.frame.size.width + (btn.originX / _btnTotalFloat) * self.contentView.frame.origin.x;
                }
                else{
                    frame.origin.x = self.frame.size.width - btn.originX + (_btnTotalFloat + self.contentView.frame.origin.x) * btn.speed;
                }
            }
            btn.frame = frame;
        }
    }
    else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

-(void)dealloc{
    [self.contentView removeObserver:self forKeyPath:@"frame"];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    if (self.delegate && [self.delegate respondsToSelector:@selector(hiddenSideslipAll)]) {
        [self.delegate hiddenSideslipAll];
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    if (_btnContainView) {
        
        _btnContainView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        
        for (UIButton *btn in _btnContainView.subviews) {
            CGRect frame = btn.frame;
            frame.size.height = self.frame.size.height;
            btn.frame = frame;
            for (UIButton *b in btn.subviews) {
                CGRect frame = b.frame;
                frame.size.height = self.frame.size.height;
                b.frame = frame;
            }
        }
        
    }
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    
    UIPanGestureRecognizer *gesture = (UIPanGestureRecognizer *)gestureRecognizer;
    CGPoint translation = [gesture translationInView:gesture.view];

    // 如果手势相对于水平方向的角度大于45°, 则不触发侧滑
    BOOL shouldBegin = fabs(translation.y) <= fabs(translation.x);
    if (!shouldBegin){
        
        // 若 tableView 滚动时, 则隐藏侧滑
        if (self.delegate && [self.delegate respondsToSelector:@selector(hiddenSideslipAll)]) {
            [self.delegate hiddenSideslipAll];
        }
        
        return NO;
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(hiddenSideslipWithOutSelf:)]) {
        [self.delegate hiddenSideslipWithOutSelf:self.cellIndex];
    }
    
    //没有更多按钮时需要初始化
    if (!_btnContainView) {
        [self setActions:self.actions];
    }
    
    return YES;
}


- (void)contentViewPan:(UIPanGestureRecognizer *)pan {
    CGPoint point = [pan translationInView:pan.view];
    UIGestureRecognizerState state = pan.state;
    [pan setTranslation:CGPointZero inView:pan.view];
    
    if (state == UIGestureRecognizerStateChanged) {
        CGRect frame = self.contentView.frame;
        frame.origin.x += point.x;
        if (frame.origin.x > 0) {
            frame.origin.x = 0;
        } else if (frame.origin.x < - _btnTotalFloat) {
            frame.origin.x =  (_btnTotalFloat + frame.origin.x) * 0.95 - _btnTotalFloat;
        }
        self.contentView.frame = frame;
        
    } else if (state == UIGestureRecognizerStateEnded) {
        CGPoint velocity = [pan velocityInView:pan.view];
        if (self.contentView.frame.origin.x == 0) {
            return;
        } else if (velocity.x >= 0) {
            [self hiddenSideslip];

        } else if (fabs(self.contentView.frame.origin.x) <= 15 && fabs(self.contentView.frame.origin.x) >= 0) {
            [self hiddenSideslip];
        } else if (fabs(self.contentView.frame.origin.x) >= 15 && velocity.x <= 0) {
            [self showSideslip];
        }
        
    }
}

- (void)hiddenSideslip {
    if (self.contentView.frame.origin.x == 0) return;
    
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        [self setContentViewX:0];
    } completion:^(BOOL finished) {
        [_btnContainView removeFromSuperview];
        _btnContainView = nil;
    }];
}

- (void)showSideslip {
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        [self setContentViewX:-_btnTotalFloat];
    } completion:^(BOOL finished) {
    }];
}

#pragma mark - Setter
- (void)setContentViewX:(CGFloat)x {
    CGRect frame = self.contentView.frame;
    frame.origin.x = x;
    self.contentView.frame = frame;
}

- (void)setActions:(NSArray <LYSideslipCellAction *>*)actions {
    _actions = actions;

    if (_btnContainView) {
        [_btnContainView removeFromSuperview];
        _btnContainView = nil;
    }
    _btnContainView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    [self insertSubview:_btnContainView belowSubview:self.contentView];
    _btnTotalFloat = 0.0;
    UIButton *modelBtn;
    for (int i = 0; i < actions.count; i++) {
        LYSideslipCellAction *action = actions[i];
        SideslipBtn *btn = [[SideslipBtn alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width, 0, [UIScreen mainScreen].bounds.size.width, self.frame.size.height)];
        
        btn.adjustsImageWhenHighlighted = NO;
        
        btn.backgroundColor = action.backgroundColor;
        
        if (action.title) {
            btn.btnTitle = action.title;
        }
        
        if (action.image) {
            btn.image = action.image;
        }
        
        if (action.fontSize != 0) {
            btn.fontSize = action.fontSize;
        }
        
        if (action.titleColor) {
            btn.titleColor = action.titleColor;
        }
        
        btn.speed = action.speed == 0 ? 1:action.speed;
        
        CGFloat width = [action.title boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : btn.titleLabel.font} context:nil].size.width;
        width += (action.image ? action.image.size.width : 0);//需要显示的btn宽度 为 width + action.margin*2

        _btnTotalFloat += width + action.margin*2;
        
        btn.sizeW = width + action.margin*2;
        
        btn.originX = _btnTotalFloat;
        
        btn.tag = i;
        
        if (modelBtn) {
            [_btnContainView insertSubview:btn belowSubview:modelBtn];
        }
        else{
            [_btnContainView addSubview:btn];
        }
        modelBtn = btn;
    }
}


@end


